package main

import (
	"awesomeProject2/api"
	"awesomeProject2/config"
	"awesomeProject2/db"
	"awesomeProject2/engine"
	"awesomeProject2/model"
	"fmt"
	"github.com/gorilla/mux"
	"github.com/redis/go-redis/v9"
	"math/rand"
	"net/http"
	"sync"
	"time"
)

func main() {
	db.InitDB(config.MySQLDSN)
	rdb := redis.NewClient(&redis.Options{Addr: config.RedisAddr, Password: config.RedisPass})

	matchEngine := engine.NewEngine(rdb)
	// 初始化内存挂单簿
	matchEngine.OrderBook = &engine.OrderBook{}

	userCount := 1000
	orderCount := 100000
	var wg sync.WaitGroup

	wg.Add(orderCount)

	for i := 0; i < orderCount; i++ {
		go func(i int) {
			defer wg.Done()

			userID := rand.Int63n(int64(userCount)) + 1
			price := float64(rand.Intn(1000) + 1)
			amount := float64(rand.Intn(10) + 1)
			orderType := model.BUY
			if rand.Intn(2) == 0 {
				orderType = model.SELL
			}

			order := &model.Order{
				ID:        int64(i + 1),
				UserID:    userID,
				Token:     "ETH",
				Type:      orderType,
				Price:     price,
				Amount:    amount,
				Remain:    amount,
				Status:    "OPEN",
				CreatedAt: time.Now(),
			}

			// 下单到挂单簿
			matchEngine.OrderBook.AddOrder(order)

			// 立即尝试撮合
			matchEngine.MatchDistributed("ETH")
		}(i)
	}

	wg.Wait()

	fmt.Println("所有模拟交易下单完成！")
	fmt.Printf("挂单簿买单数量: %d, 卖单数量: %d\n",
		len(matchEngine.OrderBook.BuyOrders),
		len(matchEngine.OrderBook.SellOrders))

	router := mux.NewRouter()
	apiHandler := &api.API{}
	apiHandler.RegisterRoutes(router)

	http.ListenAndServe(":8080", router)
}
